package com.ctshk.rpc.finance.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.finance.dto.paidin.PaidInListDTO;
import com.ctshk.rpc.finance.dto.supplier.SupplierDataDTO;
import com.ctshk.rpc.finance.dto.supplier.SupplierDataDetailDTO;
import com.ctshk.rpc.finance.dto.supplier.SupplierDataListDTO;
import com.ctshk.rpc.finance.entity.FinanceBillCheck;
import com.ctshk.rpc.finance.entity.FinanceSupplierData;
import com.ctshk.rpc.finance.entity.FinanceSupplierDataDetail;
import com.ctshk.rpc.finance.json.ClientInfoJson;
import com.ctshk.rpc.finance.json.FileJson;
import com.ctshk.rpc.finance.mapper.FinanceSupplierDataDetailMapper;
import com.ctshk.rpc.finance.mapper.FinanceSupplierDataMapper;
import com.ctshk.rpc.finance.req.supplier.SupplierDataAddReq;
import com.ctshk.rpc.finance.req.supplier.SupplierDataIdReq;
import com.ctshk.rpc.finance.req.supplier.SupplierDataListReq;
import com.ctshk.rpc.finance.service.IFinanceSupplierDataService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 供应商期初 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-04-12
 */
@DubboService
public class FinanceSupplierDataServiceImpl extends ServiceImpl<FinanceSupplierDataMapper, FinanceSupplierData> implements IFinanceSupplierDataService {

    @Autowired
    private FinanceSupplierDataMapper supplierDataMapper;
    @Autowired
    private FinanceSupplierDataDetailMapper supplierDataDetailMapper;

    @DubboReference
    private ISysUserService sysUserService;



    /**
     * 列表
     *
     * @param req
     * @return
     */
    @Override
    public Result<PageResponse<SupplierDataListDTO>> list(SupplierDataListReq req) {
        Page<FinanceSupplierData> iPage = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<FinanceSupplierData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(req.getSupplierId() != null,"supplier_id",req.getSupplierId());
        queryWrapper.like(StringUtils.isNotBlank(req.getContacts()),"contacts",req.getContacts());
        queryWrapper.between(req.getCreateTimeBegin() != null && req.getCreateTimeEnd() != null,"gmt_create",req.getCreateTimeBegin(),req.getCreateTimeEnd());
        queryWrapper.eq("is_deleted",0);
        Page<FinanceSupplierData> page = supplierDataMapper.selectPage(iPage, queryWrapper);
        List<FinanceSupplierData> records = page.getRecords();
        if (!CollectionUtils.isNotEmpty(records)){
            return Result.success(PageResponse.empty(page.getCurrent()));
        }
        List<SupplierDataListDTO> list = new ArrayList<>();
        records.forEach(record -> {
            SupplierDataListDTO dto = EntityUtil.copy(record,SupplierDataListDTO.class);
            //供应商期初金额列表
            List<SupplierDataDetailDTO> detailList = supplierDataDetailMapper.queryByData(record.getId());
            if (CollectionUtils.isNotEmpty(detailList)){
                dto.setDetailList(detailList);
            }
            list.add(dto);
        });
        PageResponse<SupplierDataListDTO> result = new PageResponse<>(
                list,
                page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(),
                page.getCurrent(),
                page.getSize());
        return Result.success(result);
    }

    /**
     * 详情
     *
     * @param req
     * @return
     */
    @Override
    public Result<SupplierDataDTO> detail(SupplierDataIdReq req) {
        FinanceSupplierData data = getById(req.getId());
        if (data == null || Objects.equals(data.getIsDeleted(),1)){
            throw new BusinessException(SystemError.FINANCE_ERROR_17030);
        }
        SupplierDataDTO dto = EntityUtil.copy(data,SupplierDataDTO.class);
        if (StringUtils.isNotBlank(data.getSupplierInfoJson())){
            dto.setClientInfoJson(JSON.parseObject(data.getSupplierInfoJson(),ClientInfoJson.class));
        }
        if (StringUtils.isNotBlank(data.getFilesJson())){
            dto.setFilesJson(JSON.parseArray(data.getFilesJson(), FileJson.class));
        }
        UserDTO userDTO = sysUserService.queryCacheUser(data.getCreateId());
        if (userDTO != null){
            dto.setCreateUserDept(userDTO.getDept());
            dto.setCreateUserName(userDTO.getFullName());
        }
        //供应商期初金额列表
        List<SupplierDataDetailDTO> detailList = supplierDataDetailMapper.queryByData(data.getId());
        if (CollectionUtils.isNotEmpty(detailList)){
            dto.setDetailList(detailList);
        }
        return Result.success(dto);
    }

    /**
     * 新增
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(SupplierDataAddReq req) {
        ClientInfoJson clientInfoJson = req.getClientInfoJson();
        if (clientInfoJson.getAccountId() == null){
            throw new BusinessException(SystemError.SYS_402);
        }
        //新增供应商期初
        FinanceSupplierData data = new FinanceSupplierData();
        data.setId(SnowflakeIdWorker.nextId());
        LocalDateTime now = LocalDateTime.now();
        data.setSupplierId(clientInfoJson.getAccountId());
        data.setSupplierName(clientInfoJson.getAccountName());
        data.setContacts(clientInfoJson.getContactName());
        data.setSupplierInfoJson(JSON.toJSONString(clientInfoJson));
        data.setRemark(req.getRemark());
        //附件
        if (CollectionUtils.isNotEmpty(req.getFilesJson())){
            data.setFilesJson(JSON.toJSONString(req.getFilesJson()));
        }
        data.setGmtCreate(now);
        data.setCreateId(req.getUserId());
        data.setIsDeleted(0);
        boolean save = save(data);
        if (!save){
            throw new BusinessException(SystemError.SYS_437);
        }
        //批量新增期初明细
        if (CollectionUtils.isEmpty(req.getDetailAddReqList())){
            throw new BusinessException(SystemError.SYS_402);
        }
        List<FinanceSupplierDataDetail> list = new ArrayList<>();
        req.getDetailAddReqList().forEach(detailAddReq -> {
            FinanceSupplierDataDetail detail = EntityUtil.copy(detailAddReq,FinanceSupplierDataDetail.class);
            detail.setId(SnowflakeIdWorker.nextId());
            detail.setDataId(data.getId());
            detail.setGmtCreate(now);
            detail.setCreateId(req.getUserId());
            detail.setIsDeleted(0);
            list.add(detail);
        });
        if (list.size() > 0){
            Integer batch = supplierDataDetailMapper.insertBatchSomeColumn(list);
            if (batch < list.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        return Result.success(data.getId());
    }


}
